package com.wlz.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 *  netty 编解码
 * @author wlz
 * @date 2022-07-09  2:12 下午
 */
@Slf4j
public class CodecNettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      log.info("收到服务端消息: {}", msg.toString());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端发送数据 。。。。");
//        ctx.writeAndFlush("测试 string 编解码");
//        ctx.writeAndFlush(new MyUser(2, "测试 对象编解码"));
        //  测试用protostuff 对象编解码
        ByteBuf buf = Unpooled.copiedBuffer(MyProtostuffUtil.serializer(new MyUser(2, "测试用protostuff 对象编解码")));
        ctx.writeAndFlush(buf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
